package com.tca.common.learning.webflux.springboot.reactor.client;

import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * @author zhoua
 */
public class ReactorWebClient {

    private static final String URI = "http://localhost:8080";

    public static void main(String[] args) throws InterruptedException {
        time();

        date();

        sendTime();
    }

    private static void time() throws InterruptedException {
        WebClient webClient = WebClient.create(URI);
        Mono<String> resp = webClient.get().uri("/reactor/time")
                // 异步方式获取
                .retrieve()
                // 将body解析成String
                .bodyToMono(String.class);
        resp.subscribe(System.out::println);
        TimeUnit.SECONDS.sleep(1);
    }

    private static void date() throws InterruptedException {
        WebClient webClient = WebClient.builder().baseUrl(URI).build();
        webClient
                .get().uri("/reactor/date")
                // Content-Type: application/stream+json
                .accept(MediaType.APPLICATION_STREAM_JSON)
                .exchange()
                .flatMapMany(response -> response.bodyToFlux(String.class))
                .doOnNext(System.out::println)
                .blockLast();
    }

    private static void sendTime() {
        WebClient webClient = WebClient.create(URI);
        webClient
                .get().uri("reactor/sendTime")
                .accept(MediaType.TEXT_EVENT_STREAM)
                .retrieve()
                .bodyToFlux(String.class)
                // 日志处理
                .log()
                // 取10条信息
                .take(10)
                .blockLast();
    }

}
